﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class admin_redirect : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string pagefrom = Request["pagefrom"];
        if (string.IsNullOrWhiteSpace(pagefrom))
            Response.Redirect("../Default.aspx");

        string urlparams = BuildParams();
        string returnPage = BuildreturnPage(pagefrom);

        string completeUrl = returnPage + "?" + urlparams;
        Response.Redirect(completeUrl);
    }

    private string BuildreturnPage(string previousPage)
    {
        string url = Request.Url.ToString();
        int indexOf = url.IndexOf('?');
        url = url.Substring(0, indexOf);
        url = url.Replace("redirect", previousPage);
        return url;
    }
    private string BuildParams()
    {
        string urlparams = string.Empty;
        int i = 0;
        string paramPart = string.Empty;
        foreach (string key in Request.QueryString.Keys)
        {
            if (Request.QueryString.Keys.Count - 1 == i)
                paramPart = key + "=" + Request.QueryString[key];
            else paramPart = key + "=" + Request.QueryString[key] + "&";
            if (paramPart.Contains("pagefrom")) //dont write this. not needed for redirect
            {
                // if this is the last param remove the last ampersand aswell
                if (Request.QueryString.Keys.Count - 1 == i)
                {
                    int lastIndex = urlparams.LastIndexOf('&');
                    urlparams = urlparams.Substring(0, lastIndex);
                    i++;
                    continue;
                }
                i++;
                continue;
            }
            urlparams += paramPart;
            i++;
        }
        return urlparams;
    }
}